// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/macros.h>
#include <pollux/functions/registerer.h>

namespace kumo::pollux::functions::sparksql {
    namespace {
        /// Ceil function to round up a decimal value of type decimal(p, s) to
        /// decimal(min(38, p - s + min(1, s)), 0).
        template<typename TExec>
        struct DecimalCeilFunction {
            POLLUX_DEFINE_FUNCTION_TYPES(TExec);

            template<typename A>
            void initialize(
                const std::vector<TypePtr> &inputTypes,
                const core::QueryConfig & /*config*/,
                A * /*a*/) {
                rescaleFactor_ = pollux::DecimalUtil::kPowersOfTen
                        [getDecimalPrecisionScale(*inputTypes[0]).second];
            }

            template<typename R, typename A>
            void call(R &out, const A &a) {
                const auto increment = (a % rescaleFactor_) > 0 ? 1 : 0;
                out = a / rescaleFactor_ + increment;
            }

        private:
            int128_t rescaleFactor_;
        };
    } // namespace

    void registerDecimalCeil(const std::string &prefix) {
        std::vector<exec::SignatureVariable> constraints = {
            exec::SignatureVariable(
                P2::name(),
                fmt::format(
                    "min(38, {p} - {s} + min({s}, 1))",
                    fmt::arg("p", P1::name()),
                    fmt::arg("s", S1::name())),
                exec::ParameterType::kIntegerParameter),
            exec::SignatureVariable(
                S2::name(), "0", exec::ParameterType::kIntegerParameter),
        };

        register_function<
            DecimalCeilFunction,
            LongDecimal<P2, S2>,
            LongDecimal<P1, S1> >({prefix + "ceil"}, constraints);

        register_function<
            DecimalCeilFunction,
            ShortDecimal<P2, S2>,
            LongDecimal<P1, S1> >({prefix + "ceil"}, constraints);

        register_function<
            DecimalCeilFunction,
            ShortDecimal<P2, S2>,
            ShortDecimal<P1, S1> >({prefix + "ceil"}, constraints);
    }
} // namespace kumo::pollux::functions::sparksql
